/* <utf8/pos_map.h>

   Convert a pointer into a UTF-8 piece into a row/col position.

   Copyright 2010-2014 OrlyAtomics, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#pragma once

#include <cassert>
#include <vector>

#include <utf8/piece.h>
#include <utf8/pos.h>

namespace Utf8 {

  /* Maps the end-of-line positions in a UTF-8 piece so you can
     convert a pointer into a row/col position.
     NOTE: This currently only works with LF as the end-of-line marker.
           It will break with CRLF lines, as generated by Windows. */
  class TPosMap {
    public:

    /* Maps the given piece. */
    TPosMap(const TPiece &text);

    /* The number of lines in the piece.  Never zero. */
    size_t GetLineCount() const {
      assert(this);
      return Eols.size() - 1;
    }

    /* Convert the pointer into a row/col position.
       The pointer must fall within the original piece or point at the limit of the piece. */
    TPos GetPos(const char *ptr) const;

    private:

    /* Pointers to end-of-line markers.
       This will always start with a pointer to just before the piece
       (which is the 'pretend' limit of the 'pretend' preceding line)
       and end with the limit of the piece.
       The minimum size of this vector is therefore 2. */
    std::vector<const char *> Eols;

  };  // TPosMap

}  // Utf8
